package com.gmss.crawler.module.paper.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gmss.crawler.constants.Constants;
import com.gmss.crawler.module.paper.domain.Paper;
import com.gmss.crawler.module.paper.mapper.PaperMapper;
import com.gmss.crawler.module.paper.service.IPaperService;
import com.gmss.crawler.module.patent.domain.Patent;
import com.gmss.crawler.module.patent.service.IPatentService;
import com.gmss.crawler.module.person.domain.PersonInfo;
import com.gmss.crawler.module.publication.domain.Publication;
import com.gmss.crawler.module.publication.service.IPublicationService;
import com.gmss.crawler.module.resume.domain.Resume;
import com.gmss.crawler.module.resume.service.IResumeService;
import com.gmss.crawler.utils.CommonUtils;
import com.gmss.crawler.utils.ExcelUtils;
import com.gmss.crawler.utils.OkHttp3Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

/**
 * <p>
 * 论文表 服务实现类
 * </p>
 *
 * @author Auto-generator
 * @since 2021-10-21
 */
@Slf4j
@Service
public class PaperServiceImpl extends ServiceImpl<PaperMapper, Paper> implements IPaperService {

    @Resource
    private IResumeService iResumeService;
    @Resource
    private IPaperService iPaperService;
    @Resource
    private IPatentService iPatentService;
    @Resource
    private IPublicationService iPublicationService;
    @Resource
    private PaperMapper paperMapper;

    /**
     * 根据人员姓名，中国工程科技专家库查询I:SCI论文，J:中文论文，U:Scopus论文，E:EI论文，C:会议论文，B:图书，P:专利，A:成果奖励等信息
     *
     * @param personInfo        人员信息
     * @param resourceJsonArray I:SCI论文，J:中文论文，U:Scopus论文，E:EI论文，C:会议论文，B:图书，P:专利，A:成果奖励
     * @param organizationList  工作单位，院士为：中国科学院，中国工程院，其它：工作单位
     * @return
     * @throws IOException
     * @throws InterruptedException
     */
    @Override
    public Map<String, Object> getPaperInfoByUserName(PersonInfo personInfo, JSONArray resourceJsonArray, List<String> organizationList) throws IOException, InterruptedException {
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> params = new HashMap<>();
        params.put("k", personInfo.getName());
        params.put("from", 0);
        params.put("size", 10);
        Thread.sleep(CommonUtils.randomRange(1000, 5000));
        okhttp3.Response response = OkHttp3Util.doPostJSON(Constants.SEARCH_EXPERT_NEW, JSON.toJSONString(params), 5000, 3);
        String result = response.body().string();
        if (StringUtils.isBlank(result))
            return resultMap;
        result = CommonUtils.jsonUnicodeToUtf8(result);
        JSONObject resultJson = JSON.parseObject(result);
        Integer status = resultJson.getInteger("status");
        String kId = "";
        // 别名
        String altName = "";
        // 个人简介
        String introduction = "";
        if (1 == status) {
            JSONObject dataJsonObject = resultJson.getJSONObject("data");

            if (dataJsonObject.getBoolean("status") && dataJsonObject.getInteger("total") > 0) {
                JSONArray objs = dataJsonObject.getJSONArray("obj");

                for (int i = 0; i < objs.size(); i++) {
                    JSONObject detailJson = JSON.parseObject(objs.get(i).toString());
                    // 组织机构
                    String organization = detailJson.getString("organization");
                    // 组织机构为中国科学院，中国工程院解析，或者工作单位
                    for (String organizationParam : organizationList) {
                        if (!StringUtils.contains(organization, organizationParam)) {
                            continue;
                        }

                        // 组织机构别名
                        String altOrganization = detailJson.getString("altOrganization");
                        // 姓别 - 女：不准确
                        Integer gender = detailJson.getInteger("gender");
                        if (null != gender) {
                            if (0 == gender && StringUtils.isBlank(personInfo.getSex())) {
//                                personInfo.setSex("女");
                            } else if (1 == gender && StringUtils.isBlank(personInfo.getSex())) {
                                personInfo.setSex("男");
                            }
                        }

                        JSONObject queryPaperJSON = new JSONObject();
                        kId = detailJson.getString("kId");
                        // 别名 姓名+工作单位相同，别名为空时取第二条数据的别名，因为姓名是一样的别名也相同
                        altName = detailJson.getString("altName");
                        if (StringUtils.isNotBlank(altName))
                            altName = getAltName(personInfo, detailJson);
                        if (StringUtils.isBlank(altName)) {
                            JSONObject nextDetailJson = JSON.parseObject(objs.get(i + 1).toString());
                            altName = getAltName(personInfo, nextDetailJson);
                        }
                        if (StringUtils.isBlank(altName)) {
                            JSONObject nextDetailJson = JSON.parseObject(objs.get(i + 2).toString());
                            altName = getAltName(personInfo, nextDetailJson);
                        }

                        // 别名
                        if (StringUtils.isNotBlank(altName) && StringUtils.isBlank(personInfo.getAltName()))
                            personInfo.setAltName(altName);
                        // 个人简介
                        introduction = detailJson.getString("introduction");
                        if (StringUtils.isNotBlank(introduction) && !StringUtils.contains(introduction, "（专家）") && StringUtils.isBlank(personInfo.getDescribeData())) {
                            personInfo.setDescribeData(introduction);
                        }

                        // 研究方向
                        JSONArray topKeywords = dataJsonObject.getJSONArray("topKeywords");
                        List<String> keyList = new ArrayList<>();
                        if (null != topKeywords && topKeywords.size() > 0) {
                            for (Object obj : topKeywords) {
                                JSONObject topWeyWordsJsonObj = (JSONObject) obj;
                                String key = topWeyWordsJsonObj.getString("key");
                                keyList.add(key);
                            }
                        }
                        // 研究方向
                        if (CollectionUtils.isNotEmpty(keyList))
                            personInfo.setResearchContents(StringUtils.join(keyList, ","));

                        // 经历
                        String resumeData = detailJson.getString("resume");
                        if (StringUtils.isNotBlank(resumeData)) {
                            // 解析经历，并入库。不太正确需要再验证，如：personId=6577
                            handleResumeAndSave(personInfo, resumeData);
                        }

                        // 学位
                        String degree = detailJson.getString("degree");
                        if (StringUtils.isNotBlank(degree) && StringUtils.isBlank(personInfo.getAcademicDegree()))
                            personInfo.setAcademicDegree(degree);
                        // 职称
                        String positionalTitle = detailJson.getString("positionalTitle");
                        if (StringUtils.isNotBlank(positionalTitle) && StringUtils.isBlank(personInfo.getPersonTitle()))
                            personInfo.setPersonTitle(positionalTitle);

                        if (StringUtils.isNotBlank(altName)) {
                            // 封装查询论文、专利、出版物的入参
                            try {
                                queryPaperJSON.put("kId", Long.parseLong(kId));
                            } catch (NumberFormatException e) {
                                JSONArray array = new JSONArray();
                                array.add(detailJson);
                                queryPaperJSON.put("nameOrgArray", array);
                            }
                            List<String> list = new ArrayList<>();
                            queryPaperJSON.put("from", 0);
                            queryPaperJSON.put("isClaimed", 1);
                            queryPaperJSON.put("order", "desc");
                            queryPaperJSON.put("size", 10);
                            queryPaperJSON.put("sort", "year");
                            if (null != resourceJsonArray && resourceJsonArray.size() > 0) {
                                queryPaperJSON.put("resource", resourceJsonArray);
                            } else {
                                queryPaperJSON.put("resource", Constants.RESOURCE_CODE);
                            }
                            queryPaperJSON.put("keywords", list);
                            queryPaperJSON.put("coauthor", list);
                            queryPaperJSON.put("ck", list);
                            queryPaperJSON.put("altName", altName);
                            queryPaperJSON.put("altOrganization", altOrganization);
                            resultMap.put("queryPaperJSON", queryPaperJSON);
                        }
                        break;
                    }
                    if (MapUtils.isNotEmpty(resultMap) && resultMap.containsKey("queryPaperJSON")) {
                        break;
                    }
                }
            }
        }
        resultMap.put("personInfo", personInfo);
        return resultMap;
    }

    /**
     * 获取别名
     *
     * @param personInfo
     * @param detailJson
     * @return
     */
    private String getAltName(PersonInfo personInfo, JSONObject detailJson) {
        String altName = detailJson.getString("altName");
        if (StringUtils.isNotBlank(altName)) {
            String[] altNames = altName.replaceAll("；", ";").split(";");
            StringBuilder sb = new StringBuilder();
            for (int j = 0; j < altNames.length; j++) {
                if (StringUtils.isNotBlank(altNames[j]) && !StringUtils.equals(CommonUtils.replaceBlank(altNames[j]), personInfo.getName()))
                    sb.append(altNames[j]).append(";");
            }
            altName = sb.toString();
        }
        return altName;
    }

    /**
     * 解析经历，并入库
     *
     * @param personInfo
     * @param resumeData
     */
    private void handleResumeAndSave(PersonInfo personInfo, String resumeData) {
        String[] resumeDatas = resumeData.split("\\|");
        List<Resume> resumeList = new ArrayList<>();
        if (resumeDatas.length > 0) {
            for (String resu : resumeDatas) {
                String[] res = resu.split(":");
                if (res.length > 1 && StringUtils.isNotBlank(res[1])) {
                    String[] dataDescs = res[1].split("\\%");
                    if (dataDescs.length > 0) {
                        for (String datas : dataDescs) {
                            Resume resume = new Resume();
                            String[] data = datas.split("\\^");
                            if (data.length >= 5) {
                                if (data[2].contains("B")) {
                                    resume.setResumeDate(data[2].replaceAll("B", ""));
                                    resume.setResume(data[1].replaceAll("A", "") + " " + data[3].replaceAll("C", "").replaceAll("D", "").replaceAll("E", "").replaceAll("F", "")
                                            + "-" + data[4].replaceAll("C", "").replaceAll("D", "").replaceAll("E", "").replaceAll("F", ""));
                                    resume.setFormat(false);
                                } else if (data[1].contains("A")) {
                                    resume.setResumeDate(data[1].replaceAll("A", "") + " " + data[3].replaceAll("C", "").replaceAll("D", "").replaceAll("E", "").replaceAll("F", "")
                                            + " " + data[4].replaceAll("C", "").replaceAll("D", "").replaceAll("E", "").replaceAll("F", ""));
                                    resume.setResume(data[1].replaceAll("A", ""));
                                }
                            } else if (data.length >= 4) {
                                if (data[2].contains("B")) {
                                    resume.setResumeDate(data[2].replaceAll("B", ""));
                                    resume.setResume(data[1].replaceAll("A", "") + " " + data[3].replaceAll("C", "").replaceAll("D", "").replaceAll("E", "").replaceAll("F", ""));
                                    resume.setFormat(false);
                                } else if (data[1].contains("A")) {
                                    resume.setResumeDate(data[1].replaceAll("A", "") + " " + data[3].replaceAll("C", "").replaceAll("D", "").replaceAll("E", "").replaceAll("F", ""));
                                    resume.setResume(data[1].replaceAll("A", ""));
                                }
                            } else if (data.length >= 3) {
                                if (data[2].contains("B")) {
                                    resume.setResumeDate(data[2].replaceAll("B", ""));
                                    resume.setResume(data[1].replaceAll("A", ""));
                                    resume.setFormat(false);
                                } else if (data[1].contains("A")) {
                                    resume.setResumeDate(data[1].replaceAll("A", "") + " " + data[2].replaceAll("C", "").replaceAll("D", "").replaceAll("E", "").replaceAll("F", ""));
                                    resume.setResume(data[1].replaceAll("A", ""));
                                }
                            } else if (data.length >= 2) {
                                if (data[1].contains("B")) {
                                    resume.setResumeDate(data[1].replaceAll("B", ""));
                                    resume.setResume(data[0].replaceAll("A", ""));
                                    resume.setFormat(false);
                                } else if (data[0].contains("A")) {
                                    resume.setResumeDate(data[0].replaceAll("A", "") + " " + data[1].replaceAll("C", "").replaceAll("D", "").replaceAll("E", "").replaceAll("F", ""));
                                    resume.setResume(data[0].replaceAll("A", ""));
                                }
                            }
                            resumeList.add(resume);
                        }
                    }
                }
            }
        }

        iResumeService.saveResumeByPersonId(personInfo, resumeList);
    }

    /**
     * 获取论文、专利、出版物
     *
     * @return
     */
    public void getPaperPatent(JSONObject paramsJSON, Long personId) throws IOException, InterruptedException {
        if (null == paramsJSON && paramsJSON.size() > 0)
            return;
        Thread.sleep(CommonUtils.randomRange(1000, 5000));
        log.info("getPaperPatent - paramsJSON : {}", paramsJSON);
        // 查询第一页数据 ck=personName
        String path = "";
        if (paramsJSON.containsKey("kId")) {
            path = Constants.GET_RESOURCE_NEW;
        } else if (paramsJSON.containsKey("nameOrgArray")) {
            path = Constants.GET_RESOURCE_FOR_KID;
        } else {
            return;
        }
        okhttp3.Response response = OkHttp3Util.doPostJSON(path, paramsJSON.toJSONString(), 5000, 3, false);
        String result = response.body().string();
        if (StringUtils.isBlank(result))
            return;
        result = CommonUtils.jsonUnicodeToUtf8(result);
        JSONObject resultJson = JSON.parseObject(result);
        if (resultJson.containsKey("status") && resultJson.getBoolean("status")) {
            if (!resultJson.containsKey("obj")) {
                return;
            }
            JSONArray jsonArray = resultJson.getJSONArray("obj");
            if (jsonArray.size() <= 0)
                return;
            List list = new ArrayList();
            // 获取数据，论文、图书、专利数据入库 ， 第一页
            saveAcademicData(resultJson, personId, list);
            Integer size = resultJson.getInteger("size");
            Integer from = resultJson.getInteger("from");
            Integer total = resultJson.getInteger("total");
            // 计算总页数
            Integer pageSize = CommonUtils.getPages(total, size);
            // 查询分页数据，从第二页开始
            for (int i = 2; i <= 10; i++) {
                Integer newFrom = size + from;
                paramsJSON.put("from", newFrom);
                Thread.sleep(CommonUtils.randomRange(1000 * 60, 3000 * 60));
                response = OkHttp3Util.doPostJSON(path, paramsJSON.toJSONString(), 5000, 3, false);
                result = response.body().string();
                if (StringUtils.isBlank(result))
                    continue;
                result = CommonUtils.jsonUnicodeToUtf8(result);
                resultJson = JSON.parseObject(result);
                if (resultJson.containsKey("status") && resultJson.getBoolean("status")) {
                    from = resultJson.getInteger("from");
                    // 获取数据，论文、图书、专利数据入库 ， 第一页以后的数据
                    saveAcademicData(resultJson, personId, list);
                }
            }
        }
    }

    /**
     * 获取数据，论文、图书、专利数据入库
     *
     * @param resultJson
     * @param personId
     * @throws IOException
     */
    private void saveAcademicData(JSONObject resultJson, Long personId, List list) throws IOException, InterruptedException {
        JSONArray jsonArray = resultJson.getJSONArray("obj");
        log.info("获取数据，论文、图书、专利数据入库：{}", jsonArray.size());
        if (jsonArray != null && jsonArray.size() > 0)
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                // I:SCI论文，J:中文论文，U:Scopus论文，E:EI论文，C:会议论文，B:图书，P:专利，A:成果奖励
                String resourceCode = jsonObject.getString("resourceCode").toUpperCase();

                // 发表年份
                String year = jsonObject.containsKey("year") ? jsonObject.getString("year") : "";
                // 标题
                String title = jsonObject.containsKey("title") ? jsonObject.getString("title") : "";
                // 语言，中文或外文
                String languageStandard = jsonObject.containsKey("languageStandard") ? jsonObject.getString("languageStandard") : "";
                // 第一作者
                String creator = jsonObject.containsKey("creator") ? jsonObject.getString("creator") : "";
                // 全部作者
                String creatorAll = jsonObject.containsKey("creatorAll") ? jsonObject.getString("creatorAll") : "";
                // 论文唯一标识
                String doi = jsonObject.containsKey("doi") ? jsonObject.getString("doi") : "";
                // 发表期刊
                String journal = jsonObject.containsKey("journal") ? jsonObject.getString("journal") : "";
                // 单位
                String instituteStandard = jsonObject.containsKey("instituteStandard") ? jsonObject.getString("instituteStandard") : "";
                // 出版人(或机构)
                String publisher = jsonObject.containsKey("publisher") ? jsonObject.getString("publisher") : "";
                // 关键词
                String keyword = jsonObject.containsKey("keyword") ? jsonObject.getString("keyword") : "";
                // 学科
                String subject = jsonObject.containsKey("subject") ? jsonObject.getString("subject") : "";
                // 图书总页数
                String pages = jsonObject.containsKey("page") ? jsonObject.getString("page") : "";
                // 申请编号
                String applicationNo = jsonObject.containsKey("applicationNo") ? jsonObject.getString("applicationNo") : "";
                // 申请日期
                String applicationDate = jsonObject.containsKey("applicationDate") ? jsonObject.getString("applicationDate") : "";
                // 归属行业
                String domain = jsonObject.containsKey("domain") ? jsonObject.getString("domain") : "";
                // 专利号
                String patentNo = jsonObject.containsKey("patentNo") ? jsonObject.getString("patentNo") : "";
                // 专利类型
                String patentType = jsonObject.containsKey("type") ? jsonObject.getString("type") : "";
                // 专利公开公告日
                String publicationDate = jsonObject.containsKey("publicationDate") ? jsonObject.getString("publicationDate") : "";
                // 摘要
                String abstractDetail = "";
                String resourceId = jsonObject.containsKey("resourceId") ? jsonObject.getString("resourceId") : "";


                // I:SCI论文，J:中文论文，U:Scopus论文，E:EI论文，C:会议论文，B:图书，P:专利，A:成果奖励
                switch (resourceCode) {
                    case "I":
                        // 获取论文摘要
//                        abstractDetail = getPaperAbstract(abstractDetail, resourceId);
                        handlePaper(year, title, languageStandard, creator, creatorAll, doi, subject,
                                journal, instituteStandard, publisher, keyword, abstractDetail, personId, 0, list);
                        break;
                    case "J":
                        // 获取论文摘要
//                        abstractDetail = getPaperAbstract(abstractDetail, resourceId);
                        handlePaper(year, title, languageStandard, creator, creatorAll, doi, subject,
                                journal, instituteStandard, publisher, keyword, abstractDetail, personId, 1, list);
                        break;
                    case "U":
                        handlePaper(year, title, languageStandard, creator, creatorAll, doi, subject,
                                journal, instituteStandard, publisher, keyword, abstractDetail, personId, 2, list);
                        break;
                    case "E":
                        handlePaper(year, title, languageStandard, creator, creatorAll, doi, subject,
                                journal, instituteStandard, publisher, keyword, abstractDetail, personId, 3, list);
                        break;
                    case "C":
                        handlePaper(year, title, languageStandard, creator, creatorAll, doi, subject,
                                journal, instituteStandard, publisher, keyword, abstractDetail, personId, 4, list);
                        break;
                    case "B":
                        handlePublication(year, title, languageStandard, pages, creatorAll, keyword, personId, list);
                        break;
                    case "P":
                        handlePatent(title, languageStandard, creator, creatorAll, applicationDate, applicationNo,
                                domain, patentNo, patentType, publicationDate, instituteStandard, personId, list);
                        break;
                }
            }

    }

    /**
     * 处理专利数据,并入库
     *
     * @param title             名称
     * @param languageStandard  语言，中文或外文
     * @param creator           申请人
     * @param creatorAll        全部申请人
     * @param applicationDate   申请时间
     * @param applicationNo     申请编号
     * @param domain            归属行业
     * @param patentNo          专利号
     * @param patentType        专利类型
     * @param publicationDate   公开公告日
     * @param instituteStandard 申请单位
     */
    private void handlePatent(String title, String languageStandard, String creator, String creatorAll, String applicationDate, String applicationNo,
                              String domain, String patentNo, String patentType, String publicationDate, String instituteStandard, Long personId, List saveList) {
        Patent patent = new Patent().builder().personId(personId).build();
        patent.setPatentName(title);
        patent.setPatentType(patentType);
        patent.setApplyNum(applicationNo);
        patent.setApplyDate(applicationDate);
        patent.setInstituteStandard(instituteStandard);
        patent.setPatentNum(patentNo);
        patent.setProposer(creatorAll);
        patent.setPublicAnnouncementDate(publicationDate);
        patent.setDomain(domain);
        if (StringUtils.isNotBlank(languageStandard) && StringUtils.equals(languageStandard, "中文"))
            patent.setLanguageStandard(0);
        else if (StringUtils.isNotBlank(languageStandard) && StringUtils.equals(languageStandard, "外文"))
            patent.setLanguageStandard(1);

        final LambdaQueryWrapper<Patent> lambda = new QueryWrapper<Patent>().lambda();
        lambda.eq(Patent::getPersonId, patent.getPersonId());
        lambda.eq(Patent::getPatentName, patent.getPatentName());
        lambda.eq(Patent::getPatentNum, patent.getPatentNum());
        List<Patent> list = iPatentService.list(lambda);
        if (CollectionUtils.isNotEmpty(list)) {
            patent.setId(list.get(0).getId());
//            iPatentService.saveOrUpdate(patent);
            return;
        }
        iPatentService.save(patent);
//        saveList.add(patent);
    }

    /**
     * 处理图书数据,并入库
     *
     * @param year             出版年份
     * @param title            名称
     * @param languageStandard 语言，中文或外文
     * @param pages            总页数
     * @param creatorAll       全部作者
     * @param keyword          关键词
     */
    private void handlePublication(String year, String title, String languageStandard, String pages, String creatorAll, String keyword, Long personId, List saveList) {
        Publication publication = new Publication().builder().personId(personId).build();
        publication.setTitle(title);
        publication.setPages(pages);
        publication.setPublicationDate(year);
        publication.setAuthors(creatorAll);
        publication.setKeyword(keyword);
        if (StringUtils.isNotBlank(languageStandard) && StringUtils.equals(languageStandard, "中文"))
            publication.setLanguageStandard(0);
        else if (StringUtils.isNotBlank(languageStandard) && StringUtils.equals(languageStandard, "外文"))
            publication.setLanguageStandard(1);

        final LambdaQueryWrapper<Publication> lambda = new QueryWrapper<Publication>().lambda();
        lambda.eq(Publication::getPersonId, publication.getPersonId());
        lambda.eq(Publication::getTitle, publication.getTitle());
        lambda.eq(Publication::getAuthors, publication.getAuthors());
        List<Publication> list = iPublicationService.list(lambda);
        if (CollectionUtils.isNotEmpty(list)) {
            publication.setId(list.get(0).getId());
//            iPublicationService.saveOrUpdate(publication);
            return;
        }
        iPublicationService.save(publication);
    }

    /**
     * 处理论文数据,并入库
     *
     * @param year              发表年份
     * @param title             标题
     * @param languageStandard  语言，中文或外文
     * @param creator           作者
     * @param creatorAll        全部作者
     * @param doi               论文唯一标识
     * @param journal           发表期刊
     * @param instituteStandard 单位
     * @param publisher         出版人(或机构)
     * @param keyword           关键词
     * @param abstractDetail    摘要
     * @param paperType         论文类型
     */
    private void handlePaper(String year, String title, String languageStandard, String creator, String creatorAll,
                             String doi, String subject, String journal, String instituteStandard, String publisher, String keyword,
                             String abstractDetail, Long personId, int paperType, List saveList) {
        Paper paper = new Paper().builder().personId(personId).build();
        paper.setPublicationDate(year);
        paper.setTitle(title);
        paper.setFirstAuthor(creator);
        paper.setOtherAuthor(creatorAll);
        paper.setDoi(doi);
        paper.setPeriodical(journal);
        paper.setPaperType(paperType);
        if (StringUtils.isNotBlank(languageStandard) && StringUtils.equals(languageStandard, "中文"))
            paper.setLanguageStandard(0);
        else if (StringUtils.isNotBlank(languageStandard) && StringUtils.equals(languageStandard, "外文"))
            paper.setLanguageStandard(1);
        paper.setKeyword(keyword);
        paper.setPublisher(publisher);
        paper.setInstituteStandard(instituteStandard);
        paper.setSubject(subject);
        paper.setDescribeData(abstractDetail);

        final LambdaQueryWrapper<Paper> lambda = new QueryWrapper<Paper>().lambda();
        if (StringUtils.isNotBlank(doi)) {
            lambda.eq(Paper::getDoi, paper.getDoi());
        } else {
            lambda.eq(Paper::getTitle, paper.getTitle());
        }
        lambda.eq(Paper::getPersonId, paper.getPersonId());
        // 同一篇论文有可能发布到SCI、EI上。
        lambda.eq(Paper::getPaperType, paperType);
        List<Paper> list = iPaperService.list(lambda);
        if (CollectionUtils.isNotEmpty(list)) {
            paper.setId(list.get(0).getId());
            iPaperService.saveOrUpdate(paper);
            return;
        }
        iPaperService.save(paper);
    }

    /**
     * 获取论文摘要,I:SCI论文，J:中文论文这两个有摘要
     *
     * @param abstractDetail
     * @param resourceId
     * @return
     * @throws IOException
     */
    private String getPaperAbstract(String abstractDetail, String resourceId) {
        try {
            if (StringUtils.isNotBlank(resourceId)) {
                JSONObject paramsJSON = new JSONObject();
                paramsJSON.put("id", resourceId);
                Thread.sleep(CommonUtils.randomRange(1000, 5000));
                okhttp3.Response response = OkHttp3Util.doPostJSON(Constants.GET_PAPER_ABSTRACT, paramsJSON.toJSONString(), 5000, 1, false);
                String paperAbstract = response.body().string();
                if (StringUtils.isNotBlank(paperAbstract)) {
                    paperAbstract = CommonUtils.jsonUnicodeToUtf8(paperAbstract);
                    JSONObject paperAbstractJson = JSON.parseObject(paperAbstract);
                    if (paperAbstractJson.containsKey("data") && paperAbstractJson.getJSONObject("data").getBoolean("result")) {
                        JSONObject abstractJSON = paperAbstractJson.getJSONObject("data");
                        if (null != abstractJSON && abstractJSON.size() > 0 && abstractJSON.containsKey("result") && abstractJSON.getBoolean("result")) {
                            JSONArray objJsonArray = abstractJSON.getJSONArray("obj");
                            if (null != objJsonArray && objJsonArray.size() > 0) {
                                // 中文论文摘要
                                abstractDetail = ((JSONObject) objJsonArray.get(0)).getString("abstract");
                                if (StringUtils.isBlank(abstractDetail)) {
                                    // SCI论文摘要
                                    abstractDetail = ((JSONObject) objJsonArray.get(0)).getString("abstractAlt");
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("获取论文摘要失败！Exception：{}", e);
        }
        return abstractDetail;
    }


    /**
     * 查询数据库，查出论文封装到list中
     *
     * @param map
     * @return
     */
    @Override
    public List<Paper> queryPaperData(Map<String, Object> map) {
        List<Paper> list = paperMapper.queryPaperData(map);
        return list;
    }

    /**
     * 把list中的论文信息写入excel
     *
     * @param filePath
     * @param fileName
     * @param patentList
     * @return
     */
    @Override
    public boolean writeExcel(String filePath, String fileName, List<Paper> patentList) {
        List<LinkedHashMap<String, Object>> list = convertExcel(patentList);
        return ExcelUtils.exportExcel(fileName, filePath, list, 65000);
//        return ExcelUtils.saveExcel(fileName, filePath, list);
    }

    /**
     * 把接收的patentList转换成excel需要的形式
     *
     * @param lists
     * @return
     */
    public List<LinkedHashMap<String, Object>> convertExcel(List<?> lists) {
        List<LinkedHashMap<String, Object>> rows = new ArrayList<>();
        Object object = lists.get(0);
        if (object instanceof Paper) {
            List<Paper> list = (List<Paper>) lists;
            for (Paper paper : list) {
                LinkedHashMap<String, Object> row = new LinkedHashMap<>();
                row.put("标识", paper.getPersonId());
                row.put("姓名", StringUtils.isNotBlank(paper.getName()) ? paper.getName() : "");
                row.put("头衔", StringUtils.isNotBlank(paper.getAcademicianTitleValue()) ? paper.getAcademicianTitleValue() : "");
                row.put("标题", StringUtils.isNotBlank(paper.getTitle()) ? paper.getTitle() : "");
                row.put("doi", StringUtils.isNotBlank(paper.getDoi()) ? paper.getDoi() : "");
                if (paper.getPaperType() != null) {
                    if (paper.getPaperType() == 0) {
                        row.put("论文类型", "SCI论文");
                    }
                    if (paper.getPaperType() == 1) {
                        row.put("论文类型", "中文论文");
                    }
                    if (paper.getPaperType() == 2) {
                        row.put("论文类型", "Scopus论文");
                    }
                    if (paper.getPaperType() == 3) {
                        row.put("论文类型", "EI论文");
                    }
                    if (paper.getPaperType() == 4) {
                        row.put("论文类型", "会议论文");
                    }
                } else {
                    row.put("论文类型", "");
                }
                if (paper.getLanguageStandard() != null) {
                    if (paper.getLanguageStandard() == 0) {
                        row.put("语言", "中文");
                    } else {
                        row.put("语言", "外文");
                    }

                } else {
                    row.put("语言", "");
                }
                row.put("关键词", StringUtils.isNotBlank(paper.getKeyword()) ? paper.getKeyword() : "");
                row.put("第一作者", StringUtils.isNotBlank(paper.getFirstAuthor()) ? paper.getFirstAuthor() : "");
                row.put("其它作者", StringUtils.isNotBlank(paper.getOtherAuthor()) ? paper.getOtherAuthor() : "");
                row.put("发表期刊", StringUtils.isNotBlank(paper.getPeriodical()) ? paper.getPeriodical() : "");
                row.put("发表日期", StringUtils.isNotBlank(paper.getPublicationDate()) ? paper.getPublicationDate() : "");
                row.put("出版人(或机构)", StringUtils.isNotBlank(paper.getPublisher()) ? paper.getPublisher() : "");
                row.put("学科", StringUtils.isNotBlank(paper.getSubject()) ? paper.getSubject() : "");
                row.put("申请单位", StringUtils.isNotBlank(paper.getInstituteStandard()) ? paper.getInstituteStandard() : "");
                rows.add(row);
            }
        }
        return rows;
    }

}
